package me.zhanshi123.invitelink;

import com.google.common.base.Charsets;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConfigManager {

    private FileConfiguration config = new YamlConfiguration();
    private File f = null;

    public ConfigManager() {
        load();
    }

    public void load() {
        try {
            Main plugin = Main.getInstance();
            f = new File(plugin.getDataFolder(), "config.yml");
            if (!f.exists()) {
                plugin.saveResource("config.yml", false);
            }
            config.load(new BufferedReader(new InputStreamReader(new FileInputStream(f), Charsets.UTF_8)));
            ConfigurationSection award = config.getConfigurationSection("awards");
            if (award != null) {
                award.getKeys(false).forEach(amount -> {
                    int intAmount = Integer.parseInt(amount);
                    awards.put(intAmount, award.getStringList(amount));
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getConnectionName() {
        return config.getString("connection", "default");
    }

    public String getUrl() {
        return config.getString("url");
    }

    private Map<Integer, List<String>> awards = new HashMap<>();

    public Map<Integer, List<String>> getReachedAwards(int amount) {
        Map<Integer, List<String>> reachedAwards = new HashMap<>(awards);
        awards.entrySet().stream()
                .filter(entry -> entry.getKey() > amount)
                .forEach(entry -> reachedAwards.remove(entry.getKey()));
        return reachedAwards;
    }
}
